package com.offcn.question.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

//import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.offcn.question.entity.TypeEntity;
import com.offcn.question.service.TypeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.offcn.question.entity.QuestionEntity;
import com.offcn.question.service.QuestionService;
import com.offcn.utils.PageUtils;
import com.offcn.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * @author longchen
 * @email liuchangrui@huawei.com
 * @date 2022-08-03 11:45:02
 */
@RestController
@RequestMapping("question/question")
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private TypeService typeService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("question:question:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = questionService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("question:question:info")
    public R info(@PathVariable("id") Long id) {
        QuestionEntity question = questionService.getById(id);
        return R.ok().put("question", question);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("question:question:save")
    public R save(@RequestBody QuestionEntity question) {
        questionService.save(question);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("question:question:update")
    public R update(@RequestBody QuestionEntity question) {
        questionService.updateById(question);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("question:question:delete")
    public R delete(@RequestBody Long[] ids) {
        questionService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 导入题目数据
     *
     * @param file
     * @return file
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        Map result = questionService.importExcel(file);
        return R.ok().put("result", result.get("result")).put("msg", result.get("msg")).put("num", result.get("num"));
    }

    /**
     * 导出题目数据
     *
     * @param tableName
     * @param response
     */
    @GetMapping("exportExcel")
    public void export(String tableName, HttpServletResponse response) {
        System.out.println("导出excele");
        Workbook workbook = questionService.exportExcel();
        if (workbook != null) {
            String fileName = "uxue_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
            //Content-Disposition:attachment，以附件的形式下载
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            //application/octet-stream:告知浏览器这是一个字节流，浏览器处理字节流的默认方式就是下载
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream;
            try {
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                response.getWriter().print("error");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下载题库模板
     *
     * @param fileName
     * @param response
     */
    @GetMapping("/download")
    public void fileDownload(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        InputStream in;
        BufferedInputStream bis;
        ServletOutputStream outputStream = null;
        try {
            String uploadPath = "B:/Download/";
            in = new FileInputStream(uploadPath + File.separator + fileName);
            bis = new BufferedInputStream(in);
            response.setHeader("content-type", "application/force-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            in.close();
            System.out.println("下载成功");
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 题目类型统计表
     *
     * @return map
     */
    @RequestMapping("countTypeQuestion")
    public R countTypeQuestion() {
        List<Map<String, Object>> mapList = questionService.countTypeQuestion();
        for (Map<String, Object> map : mapList) {
            //根据分类id，读取对应的分类数据
            Long typeId = (Long) map.get("type");
            TypeEntity typeEntity = typeService.getById(typeId);
            //重新封装分类名称到map
            map.put("name", typeEntity.getType());
        }
        return R.ok().put("mapList", mapList);
    }

}
